import com.google.appengine.api.datastore.KeyFactory
import com.google.appengine.api.images.* 

if (params["id"]) {
	
 def id = Long.parseLong(params["id"])

 try {
   def key = KeyFactory.createKey("foto", id)
   def imagen = datastore.get(key)
   
   if (imagen.imagen) {
	   byte[] bytes = imagen.imagen.getBytes()
	   
	   
       def width = 100 
       def height = 100 
       if ( width && height ){ 
    	     Image oldImage = ImagesServiceFactory.makeImage(bytes) 
    	   	 CompositeTransform cp = ImagesServiceFactory.makeCompositeTransform()
    	   	 Transform resize = ImagesServiceFactory.makeResize(50,50)
    	   	 cp.concatenate( resize )
    	   	 Image pic = images.applyTransform( cp, oldImage, ImagesService.OutputEncoding.valueOf("JPEG"))
			 //response.setContentType("application/octet-stream")
    	   	 response.setContentType("image/jpeg")
			 sout << pic.imageData

    	   
           /*Transform resize = ImagesServiceFactory.makeResize(width.toInteger(), 
        		   	height.toInteger());
    	   
    	   Image newImage = 
        	   images.applyTransform(resize, oldImage, ImagesService.OutputEncoding.valueOf("JPEG"))
        	   */
           
           
           //byte[] img = oldImage.getImageData(); 
    	   //sout << img
       } 	   
	   
	   //muestraFoto(bytes)
	   
	   
   } else {
	   println "no hay foto...."
   }

   } catch (Throwable t) {
	   println "error..........." + t
    //forward to some error page...
   }
} else {
	html.div {
		h1 ('no hay banda')
	}
}


def muestraFoto(def foto) {
	String contentType = "application/octet-stream"
	response.setContentType(contentType)
    response.setContentLength(foto.length)
    sout.write(foto)    
    sout.flush()
    sout.close()
}

def muestraImagen(def imagen) {
	String contentType = "application/octet-stream"
	
	int contentLength = imagen.length

    response.reset()

    if (imagen != null) {
        response.setContentType(contentType)
        response.setContentLength(contentLength)
        output = new BufferedOutputStream(response.getOutputStream())

        output.write(imagen)
    }
	
	
}